<template>
  <div class="p-6 bg-gray-100 min-h-screen">
    <div class="input-view">
    <h2 class="text-2xl font-bold mb-4">批量添加学生到课程</h2>
    </div>
    <div class="mb-4 flex items-center">
      <input ref="fileInput" type="file" accept=".xls,.xlsx" class="hidden" @change="onFileChange" />
      <button class="px-4 py-2 bg-blue-500 text-white rounded mr-4" @click="fileInput.click()">
        选择 Excel 文件
      </button>
      <input
        v-model="fileName"
        readonly
        placeholder="未选择文件"
        class="flex-1 border rounded p-2 bg-white"
      />
    </div>
    <div class="box-button"></div>
    <el-button type="primary" @click="gotoCourseStuManage">返回</el-button>
    <el-button class="view-button" type="primary" :disabled="students.length === 0" @click="previewDialog = true">
      预览学生信息
    </el-button>

    <el-dialog
      title="学生信息预览"
      v-model:visible="previewDialog"
      width="50%"
    >
      <el-table :data="students" stripe style="width: 100%">
        <el-table-column prop="name" label="学生姓名" />
        <el-table-column prop="email" label="学生邮箱" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onCancel">取消</el-button>
          <el-button type="primary" @click="onConfirm">确认上传</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import router from '@/router'
import * as XLSX from 'xlsx'
import axios from 'axios'
import { useCookies } from 'vue3-cookies'
import { ElMessage } from 'element-plus'

const fileInput = ref(null)
const fileName = ref('')
const students = ref([])
const previewDialog = ref(false)
const { cookies } = useCookies()

function gotoCourseStuManage(){
    router.push({path: '/teacher/courseManage/courseStuManage'})
}

function onFileChange(e) {
  const file = e.target.files[0]
  if (!file) return
  fileName.value = file.name
  const reader = new FileReader()
  reader.onload = evt => {
    const data = new Uint8Array(evt.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const sheet = workbook.Sheets[workbook.SheetNames[0]]
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 })
    const parsed = []
    for (let i = 1; i < rows.length; i++) {
      const row = rows[i]
      if (row && row[0] && row[1]) {
        parsed.push({ name: row[0], email: row[1] })
      }
    }
    students.value = parsed
  }
  reader.readAsArrayBuffer(file)
}

async function onConfirm() {
  previewDialog.value = false
  if (students.value.length === 0) return
  const courseCookie = cookies.get('selectedCourse')
  const courseID = courseCookie?.id
  if (!courseID) {
    ElMessage.error('未找到选中课程信息')
    return
  }
  try {
    for (const stu of students.value) {
      // 获取学生ID
      const userResp = await axios.get('/api/customer/user/email', { params: { email: stu.email } })
      if (userResp.data?.code !== 200) {
        ElMessage.warning(`未找到邮箱 ${stu.email} 的用户`) 
        continue
      }
      const studentID = userResp.data.data.id
      // 添加到课程
      await axios.post('/api/course/add-student', null, {
        params: { studentID, courseID }
      })
    }
    ElMessage.success('学生添加完成')
    // 重置
    students.value = []
    fileName.value = ''
  } catch (err) {
    console.error(err)
    ElMessage.error('上传过程中发生错误')
  }
}

function onCancel() {
  previewDialog.value = false
}
</script>

<style scoped>
/* Tailwind + Element Plus 样式，无额外自定义 */
.dialog-footer {
  text-align: right;
}
.dialog-footer .el-button + .el-button {
  margin-left: 8px;
}
.view-button {
  margin-left: 120px;
}
.box-button {
  margin-top: 80px ;
}
.input-view{
  margin-bottom: 80px;
}
</style>
